
let fs=require('fs');

var GET=function(info,id,fn){
	this.container=[];
	this.content={};
	this.id=id;
	this.fn=fn;
	this.init(info,id);


}
GET.prototype={
	init:function(info,id){
		this.data=info;
		this.start();
	},
	start:function(){
		var data=this.data;
		for(var i in data){
			this.container.push(data[i])
		}
		this.curr=0;

		this.getContent(this.data[1])
	},
	getContent:function(info){
		var that=this;
		var par={
			bookid:this.id,
			id:info.b,
			gid:info.t!=1?info.g:0
		};
		this.fn(par).then(function(res){
			that.curr++;
			if(info.t==1){
				that.data[info.b].content=res.data[0];
			}else{
				that.data[info.b].content=res.data[0];
				that.data[info.g].content=res.data[1];
			}
			if(that.curr==that.container.length){
				var data=that.data;
				for(var v in data){
					that.content[v]={
						bid:data[v].b,
						gid:data[v].g,
						sid:data[v].s,
						content:data[v].content,
						pid:data[v].p,
						type:data[v].t
					}
				}
				array=that.content;

				let str=JSON.stringify(array);

				console.log(str);
				fs.writeFile('./json/'+that.id+'.json',str,function(error){
					if(error) {
						fs.readFile('./json/error.log','utf-8',function(error,data){
							fs.writeFile('./json/error.log',data+that.id+'/n')
						})
					}
					console.log('done! '+that.id);
				})
			}else{
				that.getContent(that.container[that.curr])
			}
		})
	}
}

module.exports.getItem=GET;